package com.zzl.test.oss.demo;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

import com.sun.mail.util.MailSSLSocketFactory;
import com.zzl.mine.tool.CalendarUtil;
import com.zzl.mine.tool.HttpClientUtil;
import com.zzl.mine.tool.StringUtil;



/**   
 * @Description:  邮件发送
 * @author chenwei   
 * @date 2017-12-11 下午9:41:42 
 * @version V1.0   
 */
public class MailConfig {
	//发送邮件的邮箱账户
	private static final String FROMEMAIL = "xxssxb@126.com";
	private static final String FROMEAddr = "xxssxb@126.com";
	private static final String FROMPASSW = "houjie1988411";//"xsb304304";
	private static final String FROMSMTP = "smtp.126.com";
	private static final String SMTP_PORT="465";
	
	/*private static final String FROMEMAIL = "13615236781@163.com";
	private static final String FROMEAddr = "13615236781@163.com";
	private static final String FROMPASSW = "houjie1988411";
	private static final String FROMSMTP = "smtp.163.com";
	private static final String SMTP_PORT="25";*///"465";
	//阿里云控制台id及秘钥
	public static final String AccessKeyId ="LTAIgGMrJS06Femx";
	public static final String AccessKeySecret="GK4c1PLxGTeNZz6KAp4MhYp6OjQkCi";
	
	static Logger logger = Logger.getLogger(MailConfig.class);
	
	/**   
	  * 以文本格式发送邮件   
	  * @param mailInfo 待发送的邮件的信息   
	  */    
    public static boolean sendTextMail(MailSenderInfo mailInfo) throws Exception{    
    	boolean flag = true;
	      // 判断是否需要身份认证    
	      MyAuthenticator authenticator = null;    
	      Properties props = mailInfo.getProperties();   
	      MailSSLSocketFactory sf = new MailSSLSocketFactory();
	      sf.setTrustAllHosts(true);
	      props.put("mail.smtp.ssl.enable", "true");
	      props.put("mail.smtp.ssl.socketFactory", sf);
	      
	//      Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
	//      final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
	      
	      props.put("mail.transport.protocol", "SMTP");
	      props.setProperty("mail.smtp.host", FROMSMTP);
	//      props.put("mail.smtp.socketFactory.class", sf);
	      props.setProperty("mail.smtp.socketFactory.fallback", "false");
	      //邮箱发送服务器端口,这里设置为465端口
	//      props.setProperty("mail.smtp.port", "25");
	//      props.setProperty("mail.smtp.socketFactory.port", "25");
	      props.put("mail.smtp.auth", "true");
	  	try {
	      if (mailInfo.isValidate()) {    
	      // 如果需要身份认证，则创建一个密码验证器    
	        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());    
	      }   
	      // 根据邮件会话属性和密码验证器构造一个发送邮件的session    
	      Session sendMailSession = Session.getDefaultInstance(props,authenticator);
	      // 根据session创建一个邮件消息    
	      Message mailMessage = new MimeMessage(sendMailSession);    
	      // 创建邮件发送者地址    
	      Address from = new InternetAddress(mailInfo.getFromAddress());    
	      // 设置邮件消息的发送者    
	      mailMessage.setFrom(from);    
	      // 创建邮件的接收者地址，并设置到邮件消息中    
	      Address to = new InternetAddress(mailInfo.getToAddress());    
	      mailMessage.setRecipient(Message.RecipientType.TO,to);    
	      // 设置邮件消息的主题    
	      mailMessage.setSubject(mailInfo.getSubject());    
	      // 设置邮件消息发送的时间    
	      mailMessage.setSentDate(new Date());    
	      // 设置邮件消息的主要内容    
	      String mailContent = mailInfo.getContent();    
	      mailMessage.setText(mailContent);    
	      // 发送邮件    
	      Transport.send(mailMessage); 
	    } catch (AddressException e) {
	    	logger.info("邮件发送异常！", e);
			e.printStackTrace();
			flag = false;
		} catch (MessagingException e) {
			logger.info("邮件发送异常！", e);
			e.printStackTrace();
			flag = false;
		}
	  	if(flag){
	  		logger.info("邮件发送成功！");
	
	  	}
        return flag;    
    }    
       
    /**   
      * 以HTML格式发送邮件   
      * @param mailInfo 待发送的邮件信息   
     * @throws AddressException 
      */    
    public static boolean sendHtmlMail(MailSenderInfo mailInfo) throws Exception {    
      // 判断是否需要身份认证    
      MyAuthenticator authenticator = null;   
      Properties pro = mailInfo.getProperties();   
      pro.setProperty("mail.smtp.ssl.enable", "true");
      //如果需要身份认证，则创建一个密码验证器     
      if (mailInfo.isValidate()) {    
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());   
      }    
      logger.info("构造一个发送邮件的session");
      // 根据邮件会话属性和密码验证器构造一个发送邮件的session    
      Session sendMailSession = Session.getDefaultInstance(pro,authenticator);    
      // 根据session创建一个邮件消息    
      Message mailMessage = new MimeMessage(sendMailSession);    
      // 创建邮件发送者地址    
      Address from;
	try {
		from = new InternetAddress(mailInfo.getFromAddress());
			// 设置邮件消息的发送者    
	      mailMessage.setFrom(from);
	      // 创建邮件的接收者地址，并设置到邮件消息中    
	      Address to = new InternetAddress(mailInfo.getToAddress());    
	      // Message.RecipientType.TO属性表示接收者的类型为TO    
	      mailMessage.setRecipient(Message.RecipientType.TO,to);    
	      // 设置邮件消息的主题    
	      mailMessage.setSubject(mailInfo.getSubject());    
	      // 设置邮件消息发送的时间    
	      mailMessage.setSentDate(new Date());    
	      // MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象    
	      Multipart mainPart = new MimeMultipart();    
	      // 创建一个包含HTML内容的MimeBodyPart    
	      BodyPart html = new MimeBodyPart();    
	      // 设置HTML内容    
	      html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");    
	      mainPart.addBodyPart(html);    
	      // 将MiniMultipart对象设置为邮件内容    
	      mailMessage.setContent(mainPart);
	      // 发送邮件    
	      Transport.send(mailMessage);  
	} catch (AddressException e) {
		logger.info("邮件发送异常！", e);
		e.printStackTrace();
		throw e;
	} catch (MessagingException e) {
		logger.info("邮件发送异常！", e);
		e.printStackTrace();
		throw e;
	}    
      
	logger.info("邮件发送成功！");
      return true;    
    }    
 
    /*
     * @title:标题
     * @content:内容
     * @type:类型,1:文本格式;2:html格式
     * @tomail:接收的邮箱
     */
    public static boolean sendMail(String title,String content,String type,String tomail) throws Exception{   
        
    	//这个类主要是设置邮件   
	     MailSenderInfo mailInfo = new MailSenderInfo();    
	     mailInfo.setMailServerHost(FROMSMTP);    
	     mailInfo.setMailServerPort(SMTP_PORT);
	     mailInfo.setValidate(true);    
	     mailInfo.setUserName(FROMEMAIL);    
	     mailInfo.setPassword(FROMPASSW);//您的邮箱密码    
	     mailInfo.setFromAddress(FROMEAddr);    
	     mailInfo.setToAddress(tomail);    
	     mailInfo.setSubject(title);    
	     mailInfo.setContent(content);   
	     //这个类主要来发送邮件   
	     if("1".equals(type)){
	    	 return sendTextMail(mailInfo);//发送文体格式    
	     }else if("2".equals(type)){
	    	 return sendHtmlMail(mailInfo);//发送html格式   
	     }
	     return false;
	   }
    /**
     * @param SMTP  	邮件服务器
     * @param PORT		端口
     * @param EMAIL		本邮箱账号
     * @param PAW		本邮箱密码
     * @param toEMAIL	对方箱账号
     * @param TITLE		标题
     * @param CONTENT	内容
     * @param TYPE		1：文本格式;2：HTML格式
     */
    public static void sendEmail(String SMTP, String PORT, String EMAIL, String PAW, String toEMAIL, String TITLE, String CONTENT, String TYPE) throws Exception{ 
        //这个类主要是设置邮件   
	     MailSenderInfo mailInfo = new MailSenderInfo();
	     mailInfo.setMailServerHost(SMTP);    
	     mailInfo.setMailServerPort(PORT);    
	     mailInfo.setValidate(true);    
	     mailInfo.setUserName(EMAIL);    
	     mailInfo.setPassword(PAW);   
	     mailInfo.setFromAddress(EMAIL);    
	     mailInfo.setToAddress(toEMAIL);    
	     mailInfo.setSubject(TITLE);    
	     mailInfo.setContent(CONTENT);    
	     //这个类主要来发送邮件   
	    if("1".equals(TYPE)){
	    	sendTextMail(mailInfo);
	    }else{
	    	sendHtmlMail(mailInfo);
	    }
	     
	   }
    /**
     * @Description 阿里云发送邮件，单发
     * @author houjie
     * @param toAddress 收件地址
     * @param subject 邮件标题
     * @param textBody 邮件内容
     * @return
     */
    public static String aliSendEmail(String toAddress,String subject,String textBody){
    	String url="https://dm.aliyuncs.com/";
    	String signStr="AccessKeyId="+AccessKeyId+"&AccountName="+FROMEMAIL
    			+ "&Action=SingleSendMail&AddressType=1&Format=json"
    			+ "&RegionId=cn-hangzhou&ReplyToAddress=true"
    			+ "&SignatureMethod=HMAC-SHA1"
    			+ "&SignatureNonce="+StringUtil.getUUID()
    			+ "&SignatureVersion=1.0"
    			+ "&Subject="+subject
    			+ "&TextBody="+textBody
    			+ "&Timestamp="+CalendarUtil.getUTCDate()+"&ToAddress="+toAddress
    			+ "&Version=2015-11-23";
    	String Signature="";
		try {
			Signature = HMACSHA1Sign.sign(signStr, AccessKeySecret);
		} catch (Exception e) {
			logger.info("签名错误！");
			e.printStackTrace();
		}
    	String result=HttpClientUtil.doGet(url+"?"+signStr+"&Signature="+Signature);
    	logger.info(toAddress+"邮件发送结果："+result);
    	return result;
    	
    }
    
    
    public static void main(String[] args) throws Exception {
    	//sendMail("小学生数学报", "尊敬的用户：欢迎你注册小学生数学报在线学习平台。跟着《小学生数学报》，一起快乐玩数学。您的邮箱校验码：123456,请勿泄漏，请在15分钟内完成验证。", "1", "490340134@qq.com");
    	//String result=aliSendEmail("490340134@qq.com","小数报邮箱验证码","你本次的验证码是123456，请在15分钟内验证。");
    	//System.out.println(result);
    	MailSenderInfo mailInfo=new MailSenderInfo();
    	mailInfo.setMailServerHost(FROMSMTP);
    	mailInfo.setFromAddress(FROMEMAIL);
    	mailInfo.setUserName(FROMEMAIL);
    	mailInfo.setPassword(FROMPASSW);
    	mailInfo.setSubject("小学生数学报");
    	mailInfo.setContent("尊敬的用户：欢迎你注册小学生数学报在线学习平台。跟着《小学生数学报》，一起快乐玩数学。您的邮箱校验码：123456,请勿泄漏，请在15分钟内完成验证。");
    	mailInfo.setToAddress("490340134@qq.com");
    	sendTextMail(mailInfo);
	}
}
